﻿using Ewell.Interface.Common.Model.Common;
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Ewell.Interface.Common.Utils
{
    public class ProcessHelper
    {
        [DllImport("user32.dll")]
        static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        const int SW_RESTORE = 9;

        const int MemoryLenth = 10240000;
        public static readonly byte[] clearBuffer = new byte[10240000];

        public static InterfaceClientResult ProcessInvoke<T>(string progarmName, T request)
        {
            LogHelper.Debug($"调用其他进程参数:{JsonConvert.SerializeObject(request)}");
            InterfaceClientResult result = new InterfaceClientResult()
            {
                success = false,
            };
            string mapName = Guid.NewGuid().ToString();
            byte[] requestBuffer = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(request));
            try
            {
                using (MemoryMappedFile mmf = MemoryMappedFile.CreateOrOpen(mapName, MemoryLenth))
                using (MemoryMappedViewAccessor accessor = mmf.CreateViewAccessor())
                {
                    accessor.WriteArray(0, clearBuffer, 0, clearBuffer.Length);
                    accessor.WriteArray(0, requestBuffer, 0, requestBuffer.Length);

                    ProcessStartInfo startInfo = new ProcessStartInfo
                    {
                        FileName = Path.Combine(Environment.CurrentDirectory, progarmName),
                        Arguments = $"{mapName} {MemoryLenth}",
                        RedirectStandardOutput = false,
                        UseShellExecute = false,
                        CreateNoWindow = true
                    };

                    try
                    {
                        using (Process process = new Process())
                        {
                            process.StartInfo = startInfo;
                            process.Start();

                            // 等待一段时间，确保目标程序已经启动
                            System.Threading.Thread.Sleep(1000);

                            // 获取目标程序的主窗口句柄
                            IntPtr hWnd = process.MainWindowHandle;

                            // 将窗口置于顶端
                            if (hWnd != IntPtr.Zero)
                            {
                                SetForegroundWindow(hWnd); // 将窗口置于顶端
                                ShowWindow(hWnd, SW_RESTORE); // 恢复窗口
                            }
                            Task task=Task.Run(() =>
                            {
                                process.WaitForExit();
                            });
                            task.Wait();
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.Debug($"调用其他进程异常:{ex}");
                        result.success = false;
                        result.message = "调用进程异常!" + ex.Message;
                        return result;
                    }
                    byte[] resultBuffer = new byte[MemoryLenth];
                    accessor.ReadArray(0, resultBuffer, 0, MemoryLenth);

                    string resultMsg = Encoding.UTF8.GetString(resultBuffer).Trim('\0');
                    result = JsonConvert.DeserializeObject<InterfaceClientResult>(resultMsg);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Debug($"调用其他进程异常:{ex}");
                result.success = false;
                result.message = ex.Message;
            }
            LogHelper.Debug($"调用其他进程返回:{JsonConvert.SerializeObject(result)}");
            return result;
        }
    }
}
